package com.liuheqiao.sushegaunli.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.liuheqiao.sushegaunli.R;
import com.liuheqiao.sushegaunli.adapter.BannerAdapter;
import com.liuheqiao.sushegaunli.adapter.NoticeAdapter;
import com.liuheqiao.sushegaunli.model.Banner;
import com.liuheqiao.sushegaunli.model.Notice;
import com.liuheqiao.sushegaunli.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private ViewPager2 viewPager;
    private Handler handler;
    private Runnable runnable;
    private static final long BANNER_DELAY = 3000;
    private LinearLayout indicatorContainer;
    private ImageView[] indicators;
    private List<Banner> banners;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        
        // 初始化视图
        initViews(view);
        // 设置轮播图
        setupBanner();
        // 设置公告列表
        setupNoticeList(view);
        
        return view;
    }

    private void initViews(View view) {
        viewPager = view.findViewById(R.id.viewPager);
        indicatorContainer = view.findViewById(R.id.ll_indicator_container);
        handler = new Handler();
    }

    private void setupBanner() {
        banners = JsonUtils.loadBannerData(requireContext());
        if (banners == null || banners.isEmpty()) return;

        // 创建循环列表
        List<Banner> infiniteBanners = new ArrayList<>();
        infiniteBanners.add(banners.get(banners.size() - 1)); // 添加最后一个到开头
        infiniteBanners.addAll(banners);
        infiniteBanners.add(banners.get(0)); // 添加第一个到结尾

        BannerAdapter bannerAdapter = new BannerAdapter(requireContext(), infiniteBanners);
        viewPager.setAdapter(bannerAdapter);
        
        setupIndicators(banners.size());
        setupAutoScroll();

        // 监听页面切换
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 更新指示器，注意要减去首个重复项
                int realPosition = (position - 1 + banners.size()) % banners.size();
                updateIndicators(realPosition);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    // 当滑动停止时检查是否需要无限循环
                    int position = viewPager.getCurrentItem();
                    if (position == 0) {
                        // 如果在第一个位置（实际是最后一张的副本），跳转到倒数第二个位置（实际的最后一张）
                        viewPager.setCurrentItem(banners.size(), false);
                    } else if (position == infiniteBanners.size() - 1) {
                        // 如果在最后一个位置（实际是第一张的副本），跳转到第二个位置（实际的第一张）
                        viewPager.setCurrentItem(1, false);
                    }
                }
            }
        });

        // 设置初始位置为第二个item（实际的第一张图）
        viewPager.setCurrentItem(1, false);
    }

    private void setupAutoScroll() {
        runnable = new Runnable() {
            @Override
            public void run() {
                if (viewPager != null && banners != null && !banners.isEmpty()) {
                    int currentItem = viewPager.getCurrentItem();
                    viewPager.setCurrentItem(currentItem + 1);
                }
                handler.postDelayed(this, BANNER_DELAY);
            }
        };
    }

    private void setupNoticeList(View view) {
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        
        List<Notice> notices = JsonUtils.loadNoticeData(requireContext());
        NoticeAdapter noticeAdapter = new NoticeAdapter(requireContext(), notices);
        recyclerView.setAdapter(noticeAdapter);
    }

    private void setupIndicators(int count) {
        if (indicatorContainer == null) return;
        
        indicators = new ImageView[count];
        indicatorContainer.removeAllViews();
        
        for (int i = 0; i < count; i++) {
            indicators[i] = new ImageView(requireContext());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.width = 24;
            params.height = 24;
            params.setMargins(8, 0, 8, 0);
            indicators[i].setLayoutParams(params);
            indicators[i].setImageResource(i == 0 ? 
                    R.drawable.indicator_selected : 
                    R.drawable.indicator_unselected);
            indicatorContainer.addView(indicators[i]);
        }
    }

    private void updateIndicators(int position) {
        if (indicators == null) return;
        
        for (int i = 0; i < indicators.length; i++) {
            indicators[i].setImageResource(
                    i == position ? 
                    R.drawable.indicator_selected : 
                    R.drawable.indicator_unselected
            );
        }
    }

    private void startAutoScroll() {
        if (handler != null && runnable != null) {
            handler.removeCallbacks(runnable);
            handler.postDelayed(runnable, BANNER_DELAY);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (handler != null && runnable != null) {
            handler.removeCallbacks(runnable);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (handler != null && runnable != null) {
            handler.removeCallbacks(runnable);
        }
        handler = null;
        viewPager = null;
        indicatorContainer = null;
        banners = null;
    }
} 